
/*
 * =====================================================================================
 *
 *       Filename:  Lock.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  02/27/19 14:25:18
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  liushuyong (), shuyong1999@163.com
 *        Company:  shuyong
 *
 * =====================================================================================
 */

#include "Lock.h"

MutexLock::MutexLock() {
    int32_t ret = bthread_mutex_init(&mMutex, NULL);

    if (0 != ret) {
        LOG(FATAL) << "[MutexLock::MutexLock][errno=" << ret << "] init mutex failed";
        abort();
    }
}

MutexLock::~MutexLock() {
    int32_t ret = bthread_mutex_destroy(&mMutex);

    if (0 != ret) {
        LOG(FATAL) << "[MutexLock::~MutexLock][errno=" << ret << "] destroy mutex failed";
        abort();
    }
}

void MutexLock::lock() {
    int32_t ret = bthread_mutex_lock(&mMutex);

    if (0 != ret) {
        LOG(FATAL) << "[MutexLock::lock][errno=" << ret << "] lock failed";
        abort();
    }
}

void MutexLock::unlock() {
    int32_t ret = bthread_mutex_unlock(&mMutex);

    if (0 != ret) {
        LOG(FATAL) << "[MutexLock::unlock][errno=" << ret << "] unlock failed";
        abort();
    }
}

RWLock::RWLock() {
    int32_t ret = bthread_rwlock_init(&mRWLock, NULL);

    if (0 != ret) {
        LOG(FATAL) << "[RWLock::RWLock][errno=" << ret << "] init rwlock failed";
        abort();
    }
}

RWLock::~RWLock() {
    int32_t ret = bthread_rwlock_destroy(&mRWLock);

    if (0 != ret) {
        LOG(FATAL) << "[RWLock::~RWLock][errno=" << ret << "] destroy rwlock failed";
        abort();
    }
}

void RWLock::setReadLock() {
    int32_t ret = bthread_rwlock_rdlock(&mRWLock);

    if (0 != ret) {
        LOG(FATAL) << "[RWLock::setReadLock][errno=" << ret << "] rwlock rdlock failed";
        abort();
    }
}

void RWLock::setWriteLock() {
    int32_t ret = bthread_rwlock_wrlock(&mRWLock);

    if (0 != ret) {
        LOG(FATAL) << "[RWLock::setWriteLock][errno=" << ret << "] rwlock wrlock failed";
        abort();
    }
}

void RWLock::unlock() {
    int32_t ret = bthread_rwlock_unlock(&mRWLock);

    if (0 != ret) {
        LOG(FATAL) << "[RWLock::unlock][errno=" << ret << "] unlock failed";
        abort();
    }
}
